/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtpserver.handler.fastfail;

import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Required;

import com.googlecode.asyncmail.common.DSNStatus;
import com.googlecode.asyncmail.common.MailAddress;
import com.googlecode.asyncmail.dnsservice.DNSService;
import com.googlecode.asyncmail.smtpserver.SMTPSession;
import com.googlecode.asyncmail.smtpserver.core.ConnectHandler;
import com.googlecode.asyncmail.smtpserver.hook.HookResult;
import com.googlecode.asyncmail.smtpserver.hook.HookReturnCode;
import com.googlecode.asyncmail.smtpserver.hook.RcptHook;

/**
 * Connect handler for DNSRBL processing
 */
public class DNSRBLHandler implements ConnectHandler, RcptHook {
    /**
     * The lists of rbl servers to be checked to limit spam
     */
    private List<String> whitelist;

    private List<String> blacklist;

    private DNSService dnsService = null;

    private boolean getDetail = false;

    private String blocklistedDetail = null;

    public static final String RBL_BLOCKLISTED_MAIL_ATTRIBUTE_NAME = "com.googlecode.asyncmail.smtpserver.rbl.blocklisted";

    public static final String RBL_DETAIL_MAIL_ATTRIBUTE_NAME = "com.googlecode.asyncmail.smtpserver.rbl.detail";

    private Log logger;

    @Required
    public void setLogger(Log logger) {
        this.logger = logger;
    }

    /**
     * check if the remote Ip address is block listed
     * 
     * @see com.googlecode.asyncmail.smtpserver.core.ConnectHandler#onConnect(SMTPSession)
     */
    public void onConnect(SMTPSession session) {
        checkDNSRBL(session, session.getRemoteIPAddress());
    }

    /**
     * Set the whitelist array
     * 
     * @param whitelist
     *                The array which contains the whitelist
     */
    public void setWhitelist(List<String> whitelist) {
        this.whitelist = whitelist;
    }

    /**
     * Set the blacklist array
     * 
     * @param blacklist
     *                The array which contains the blacklist
     */
    public void setBlacklist(List<String> blacklist) {
        this.blacklist = blacklist;
    }

    /**
     * Set for try to get a TXT record for the blocked record.
     * 
     * @param getDetail
     *                Set to ture for enable
     */
    public void setGetDetail(boolean getDetail) {
        this.getDetail = getDetail;
    }

    /**
     * 
     * This checks DNSRBL whitelists and blacklists. If the remote IP is
     * whitelisted it will be permitted to send e-mail, otherwise if the remote
     * IP is blacklisted, the sender will only be permitted to send e-mail to
     * postmaster (RFC 2821) or abuse (RFC 2142), unless authenticated.
     */

    public void checkDNSRBL(SMTPSession session, String ipAddress) {

        /*
         * don't check against rbllists if the client is allowed to relay.. This
         * whould make no sense.
         */
        if (session.isRelayingAllowed()) {
            logger.info("Ipaddress " + session.getRemoteIPAddress()
                    + " is allowed to relay. Don't check it");
            return;
        }

        if (whitelist != null || blacklist != null) {
            StringBuffer sb = new StringBuffer();
            StringTokenizer st = new StringTokenizer(ipAddress, " .", false);
            while (st.hasMoreTokens()) {
                sb.insert(0, st.nextToken() + ".");
            }
            String reversedOctets = sb.toString();

            if (whitelist != null) {
                for (int i = 0; i < whitelist.size(); i++)
                    try {
                        dnsService.getByName(reversedOctets + whitelist.get(i));
                        if (logger.isInfoEnabled()) {
                            logger.info("Connection from " + ipAddress
                                    + " whitelisted by " + whitelist.get(i));
                        }

                        return;
                    } catch (java.net.UnknownHostException uhe) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("IpAddress "
                                    + session.getRemoteIPAddress()
                                    + " not listed on " + whitelist.get(i));
                        }
                    }
            }

            if (blacklist != null) {
                for (int i = 0; i < blacklist.size(); i++)
                    try {
                        dnsService.getByName(reversedOctets + blacklist.get(i));
                        if (logger.isInfoEnabled()) {
                            logger.info("Connection from " + ipAddress
                                    + " restricted by " + blacklist.get(i)
                                    + " to SMTP AUTH/postmaster/abuse.");
                        }

                        // we should try to retrieve details
                        if (getDetail) {
                            Collection<String> txt = dnsService
                                    .findTXTRecords(reversedOctets
                                            + blacklist.get(i));

                            // Check if we found a txt record
                            if (!txt.isEmpty()) {
                                // Set the detail
                                String blocklistedDetail = txt.iterator()
                                        .next();

                                session.getConnectionState().put(
                                        RBL_DETAIL_MAIL_ATTRIBUTE_NAME,
                                        blocklistedDetail);
                            }
                        }

                        session.getConnectionState().put(
                                RBL_BLOCKLISTED_MAIL_ATTRIBUTE_NAME, "true");
                        return;
                    } catch (java.net.UnknownHostException uhe) {
                        // if it is unknown, it isn't blocked
                        if (logger.isDebugEnabled()) {
                            logger.debug("unknown host exception thrown:"
                                    + blacklist.get(i));
                        }
                    }
            }
        }
    }

    /**
     * @see com.googlecode.asyncmail.smtpserver.hook.RcptHook#doRcpt(com.googlecode.asyncmail.smtpserver.SMTPSession,
     *      org.apache.mailet.MailAddress, org.apache.mailet.MailAddress)
     */
    public HookResult doRcpt(SMTPSession session, MailAddress sender,
            MailAddress rcpt) {

        if (!session.isRelayingAllowed()) {
            String blocklisted = (String) session.getConnectionState().get(
                    RBL_BLOCKLISTED_MAIL_ATTRIBUTE_NAME);

            if (blocklisted != null) { // was found in the RBL
                if (blocklistedDetail == null) {
                    return new HookResult(
                            HookReturnCode.DENY,
                            DSNStatus.getStatus(DSNStatus.PERMANENT,
                                    DSNStatus.SECURITY_AUTH)
                                    + " Rejected: unauthenticated e-mail from "
                                    + session.getRemoteIPAddress()
                                    + " is restricted.  Contact the postmaster for details.");
                } else {
                    return new HookResult(HookReturnCode.DENY, DSNStatus
                            .getStatus(DSNStatus.PERMANENT,
                                    DSNStatus.SECURITY_AUTH)
                            + " " + blocklistedDetail);
                }

            }
        }
        return new HookResult(HookReturnCode.DECLINED);
    }

    @Required
    public void setDnsService(DNSService dnsService) {
        this.dnsService = dnsService;
    }
}
